package eu.trojanbug.maven.plugins;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file 
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied.  See the License for the 
 * specific language governing permissions and limitations 
 * under the License.
 */
import eu.trojanbug.maven.plugins.types.PropertyDescription;
import eu.trojanbug.maven.plugins.types.PropertyMapping;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.CommandLineUtils;

/**
 * The map-properties maps from a property value to a different property,
 * using regular expressions for matching (both property names and current values) and substitutions.
 *
 * @author <a href="mailto:trojanbug@gmail.com">Krzysztof Trojan</a>
 * @goal map-properties
 */
public class MapPropertiesMojo extends AbstractMojo {

    /**
     * @parameter default-value="${project}"
     * @required
     * @readonly
     */
    private MavenProject project;
    /**
     * The properties to be matched.
     *
     * @parameter
     * @required
     */
    private PropertyMapping[] mappings;
    /**
     * The prefix to add to environment variables, if empty/null environment variables are not searched.
     *
     * @parameter default-value=""
     */
    private String environmentVarablesPrefix;
    /**
     * The prefix to add to system properties, if empty or null system properties are not searched.
     *
     * @parameter default-value=""
     */
    private String systemPropertiesPrefix;
    /*
     * A string "glueing" the name and value pattern, ensuring continuos group numeration on matches
     */
    private static final String aMagicStringImpossibleToMatchAccidentally = "BB6F4E922689696FED9EC8A5F6DB808C";

    public void execute()
            throws MojoExecutionException {

        Properties projectProperties = project.getProperties();

        Properties mergedProperties = new Properties();

        if (StringUtils.isNotEmpty(environmentVarablesPrefix)) {
            try {
                Properties environment = CommandLineUtils.getSystemEnvVars();
                Iterator iter = environment.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Entry) iter.next();
                    mergedProperties.put(environmentVarablesPrefix + entry.getKey(), entry.getValue());
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        if (StringUtils.isNotEmpty(systemPropertiesPrefix)) {
            Properties systemProps = System.getProperties();
            Iterator iter = systemProps.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Entry) iter.next();
                mergedProperties.put(systemPropertiesPrefix + entry.getKey(), entry.getValue());
            }
        }

        mergedProperties.putAll(projectProperties);

        if (mappings != null) {
            for (int mappingNumber = 0; mappingNumber < mappings.length; mappingNumber++) {
                processMapping(mappings[mappingNumber], mergedProperties, projectProperties);
            }
        }
    }

    protected void processMapping(PropertyMapping mapping, Properties input, Properties output) {
        PropertyDescription from = mapping.getFrom();
        PropertyDescription to = mapping.getTo();
        if (from == null || to == null) {
            return;
        }

        Pattern namePattern = Pattern.compile(from.getName());

        Iterator it = input.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Entry) it.next();

            Matcher nameMatcher = namePattern.matcher(entry.getKey().toString());
            if (nameMatcher.matches()) {
                Pattern valuePattern = Pattern.compile(from.getName() + "(?:" + aMagicStringImpossibleToMatchAccidentally + ")" + from.getValue());
                Matcher valueMatcher = valuePattern.matcher(entry.getKey().toString() + aMagicStringImpossibleToMatchAccidentally + entry.getValue().toString());

                if (valueMatcher.matches()) {
                    StringBuffer key = new StringBuffer();
                    StringBuffer value = new StringBuffer();
                    valueMatcher.appendReplacement(key, to.getName());
                    valueMatcher.reset();
                    valueMatcher.matches();
                    valueMatcher.appendReplacement(value, to.getValue());
                    output.put(key.toString(), value.toString());
                }
            }
        }
    }
}
